package com.example.kk.netty.netty;

import android.content.Context;
import android.os.Handler;
import android.widget.TextView;

import com.example.kk.netty.MainActivity;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class HelloClientInitializer extends ChannelInitializer<SocketChannel> {

    private Handler view;
    public HelloClientInitializer(Handler view){
        this.view=view;
    }
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        /*
         * ����ط��� ����ͷ���˶�Ӧ�ϡ������޷���������ͱ���
         *
         * ����ͱ��� �ҽ�������һ��Ϊ�����ϸ�Ľ��⡣�ٴ���ʱ������ϸ������
         *
         * */
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());

        // �ͻ��˵��߼�
        pipeline.addLast("handler", new HelloClientHandler(view));
    }


//    private Context context;
//    public HelloClientInitializer(Context ctx){
//        this.context = ctx;
//    }
//
//    @Override
//    protected void initChannel(SocketChannel ch) throws Exception {
//        ChannelPipeline pipeline = ch.pipeline();
//        /**
//         * 这个地方的必须和服务端对应上。否则无法正常解码和编码
//         */
//        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
//        //客户端的逻辑
//        pipeline.addLast("handler",new HelloClientHandler(context));
//    }
//
//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg)
//            throws Exception {
//        System.out.println("---channelRead--- msg="+msg);
//        super.channelRead(ctx, msg);
//    }
//
//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("---channelReadComplete---");
//        super.channelReadComplete(ctx);
//    }

}